"""系统管理API"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_active_admin
from app.models.user import User
from app.models.document import Document
from app.services.vector_store import VectorStore
from app.core.config import settings
import os
import logging

router = APIRouter()
logger = logging.getLogger(__name__)


@router.post("/clean-orphan-vectors")
async def clean_orphan_vectors(
    current_user: User = Depends(get_current_active_admin),
    db: Session = Depends(get_db)
):
    """
    清理孤儿向量数据（仅管理员）
    
    Returns:
        dict: 清理结果报告
    """
    try:
        # 获取所有已向量化的文档ID
        valid_doc_ids = set()
        all_docs = db.query(Document).filter(Document.is_vectorized == True).all()
        
        for doc in all_docs:
            valid_doc_ids.add(doc.id)
        
        logger.info(f"数据库中共有 {len(valid_doc_ids)} 个已向量化的文档")
        
        # 检查所有向量库
        vectors_dir = os.path.join(settings.UPLOAD_DIR, "vectors")
        if not os.path.exists(vectors_dir):
            return {
                "success": True,
                "message": "向量库目录不存在，无需清理",
                "total_kb_count": 0,
                "cleaned_kb_count": 0,
                "total_removed_vectors": 0,
                "details": []
            }
        
        cleaned_kb_count = 0
        total_removed_vectors = 0
        details = []
        total_kb_count = 0
        
        # 遍历所有知识库的向量文件
        for filename in os.listdir(vectors_dir):
            if not filename.endswith('.index'):
                continue
            
            total_kb_count += 1
            kb_id = filename.replace('.index', '')
            vector_path = os.path.join(vectors_dir, kb_id)
            
            try:
                # 加载向量库
                vector_store = VectorStore()
                vector_store.load(vector_path)
                
                original_count = vector_store.count()
                
                # 找出需要删除的文档ID
                doc_ids_in_vectors = set()
                orphan_doc_ids = set()
                
                for metadata in vector_store.metadatas:
                    doc_id = metadata.get('document_id')
                    if doc_id:
                        doc_ids_in_vectors.add(doc_id)
                        if doc_id not in valid_doc_ids:
                            orphan_doc_ids.add(doc_id)
                
                if orphan_doc_ids:
                    logger.info(f"知识库 {kb_id} 发现孤儿向量: {orphan_doc_ids}")
                    
                    # 删除每个孤儿文档的向量
                    for orphan_id in orphan_doc_ids:
                        vector_store.remove_by_document_id(orphan_id)
                    
                    # 保存清理后的向量库
                    vector_store.save(vector_path)
                    
                    removed_count = original_count - vector_store.count()
                    total_removed_vectors += removed_count
                    cleaned_kb_count += 1
                    
                    details.append({
                        "kb_id": kb_id,
                        "original_vectors": original_count,
                        "removed_vectors": removed_count,
                        "remaining_vectors": vector_store.count(),
                        "orphan_doc_ids": list(orphan_doc_ids)
                    })
                else:
                    details.append({
                        "kb_id": kb_id,
                        "original_vectors": original_count,
                        "removed_vectors": 0,
                        "remaining_vectors": original_count,
                        "orphan_doc_ids": []
                    })
                    
            except Exception as e:
                logger.error(f"处理知识库 {kb_id} 时出错: {str(e)}")
                details.append({
                    "kb_id": kb_id,
                    "error": str(e)
                })
                continue
        
        logger.info(f"清理完成：处理 {total_kb_count} 个知识库，清理 {cleaned_kb_count} 个，删除 {total_removed_vectors} 个孤儿向量")
        
        return {
            "success": True,
            "message": f"清理完成！共处理 {total_kb_count} 个知识库，删除 {total_removed_vectors} 个孤儿向量",
            "total_kb_count": total_kb_count,
            "cleaned_kb_count": cleaned_kb_count,
            "total_removed_vectors": total_removed_vectors,
            "details": details
        }
        
    except Exception as e:
        logger.error(f"清理孤儿向量失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清理失败: {str(e)}")


@router.get("/health-check")
async def system_health_check(
    current_user: User = Depends(get_current_active_admin),
    db: Session = Depends(get_db)
):
    """
    系统健康检查（仅管理员）
    
    Returns:
        dict: 健康检查报告
    """
    try:
        report = {
            "database": {"status": "unknown", "details": {}},
            "vectors": {"status": "unknown", "details": {}},
            "ollama": {"status": "unknown", "details": {}},
            "storage": {"status": "unknown", "details": {}}
        }
        
        # 1. 数据库检查
        try:
            total_docs = db.query(Document).count()
            vectorized_docs = db.query(Document).filter(Document.is_vectorized == True).count()
            report["database"] = {
                "status": "healthy",
                "details": {
                    "total_documents": total_docs,
                    "vectorized_documents": vectorized_docs,
                    "connection": "ok"
                }
            }
        except Exception as e:
            report["database"] = {
                "status": "error",
                "details": {"error": str(e)}
            }
        
        # 2. 向量库检查
        try:
            vectors_dir = os.path.join(settings.UPLOAD_DIR, "vectors")
            if os.path.exists(vectors_dir):
                vector_files = [f for f in os.listdir(vectors_dir) if f.endswith('.index')]
                total_vectors = 0
                
                for filename in vector_files:
                    try:
                        kb_id = filename.replace('.index', '')
                        vector_store = VectorStore()
                        vector_store.load(os.path.join(vectors_dir, kb_id))
                        total_vectors += vector_store.count()
                    except:
                        pass
                
                report["vectors"] = {
                    "status": "healthy",
                    "details": {
                        "knowledge_base_count": len(vector_files),
                        "total_vectors": total_vectors
                    }
                }
            else:
                report["vectors"] = {
                    "status": "warning",
                    "details": {"message": "向量库目录不存在"}
                }
        except Exception as e:
            report["vectors"] = {
                "status": "error",
                "details": {"error": str(e)}
            }
        
        # 3. Ollama服务检查
        try:
            import httpx
            async with httpx.AsyncClient() as client:
                response = await client.get("http://localhost:11434/api/tags", timeout=2.0)
                if response.status_code == 200:
                    models = response.json().get('models', [])
                    report["ollama"] = {
                        "status": "healthy",
                        "details": {
                            "models_count": len(models),
                            "connection": "ok"
                        }
                    }
                else:
                    report["ollama"] = {
                        "status": "warning",
                        "details": {"message": "服务响应异常"}
                    }
        except Exception as e:
            report["ollama"] = {
                "status": "error",
                "details": {"error": str(e)}
            }
        
        # 4. 存储空间检查
        try:
            import shutil
            total, used, free = shutil.disk_usage(settings.UPLOAD_DIR)
            report["storage"] = {
                "status": "healthy" if (free / total) > 0.1 else "warning",
                "details": {
                    "total_gb": round(total / (1024**3), 2),
                    "used_gb": round(used / (1024**3), 2),
                    "free_gb": round(free / (1024**3), 2),
                    "usage_percent": round((used / total) * 100, 2)
                }
            }
        except Exception as e:
            report["storage"] = {
                "status": "error",
                "details": {"error": str(e)}
            }
        
        return {
            "success": True,
            "timestamp": str(datetime.now()),
            "report": report
        }
        
    except Exception as e:
        logger.error(f"健康检查失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"健康检查失败: {str(e)}")


from datetime import datetime

